package com.atguigu.tingshu.account.consumer;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.model.account.UserAccount;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Log4j2
public class AccountInitMessageConsumer {


    @Autowired
    UserAccountService userAccountService;

    @SneakyThrows
    @RabbitListener(queues = "account_init_queue")
    public void accountInit(Channel channel, Message message) {
        // 从message中获取userId
        Long userId = Long.valueOf(new String(message.getBody()));
        // 获取messageProperties
        MessageProperties messageProperties = message.getMessageProperties();
        // 获取deliveryTag
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            // 写库
            userAccountService.accountInit(userId);
            // 确认消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            if (messageProperties.getRedelivered()) {
                // 记录错误日志
                log.error("账户初始化失败, 用户id: " + userId + ", 失败原因: " + e.getMessage());
                // 拒绝消息
                channel.basicReject(deliveryTag, false);
            } else {
                // 重试消费
                channel.basicReject(deliveryTag, true);
            }
        }


    }

}
